package com.zhanvie.thread;

import com.zhanvie.singleton.RunState;
import com.zhanvie.config.RunningContext;
import com.zhanvie.config.TaskConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierThread implements Runnable{

    private static final Logger logger = LogManager.getLogger(CyclicBarrierThread.class);

    private static final Random random = new Random();

    @Override
    public void run() {
        try {
            while (RunState.getInstance().isRunning()) {
                logger.info("thread {} is running", Thread.currentThread().getName());
                int waitTime = random.nextInt(5000);
                TimeUnit.MILLISECONDS.sleep(waitTime);

                CyclicBarrier cyclicBarrier1 = new CyclicBarrier(TaskConfig.cyclicBarrierTestThreadCount, () -> {
                    logger.info("thread {} the latest arrive, begin to do some thing", Thread.currentThread().getName());
                    RunningContext.cyclicBarrier.remove(RunState.getInstance().getPid());
                    System.out.println();
                    RunState.getInstance().stop();
                });
                RunningContext.cyclicBarrier.putIfAbsent(RunState.getInstance().getPid(), cyclicBarrier1);
                CyclicBarrier cyclicBarrier = RunningContext.cyclicBarrier.get(RunState.getInstance().getPid());
                logger.info("thread {} is waiting", Thread.currentThread().getName());
                cyclicBarrier.await();
            }
        } catch (Throwable e) {
            logger.error("thread catch exception", e);
        } finally {
            logger.info("thread exit!");
        }

    }

}
